package com.example.music.activity;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;

import static java.lang.Integer.parseInt;
import com.example.music.adapter.SongAdapter;
import com.example.music.adapter.PlaylistAdapter;
import com.example.music.db.FavoritesDAO;
import com.example.music.db.RecentPlayDAO;
import com.example.music.fragment.PlaylistDialogFragment;
import com.example.music.model.AppConstants;
import com.example.music.model.Song;
import com.example.music.utils.LyricParser;
import com.example.music.R;
import com.example.music.fragment.SongFragment;
import com.example.music.adapter.LyricsAdapter;
import com.example.music.service.MusicService;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

import android.content.BroadcastReceiver;
import android.content.Context;

public class MusicActivity extends AppCompatActivity implements View.OnClickListener,PlaylistDialogFragment.OnSongSelectedListener{

    public static MusicActivity instance;

    //进度条
    private static SeekBar sb;
    private static TextView tv_progress,tv_total,name_song;
    //动画
    private ObjectAnimator animator;
    private ImageView imageView;
    private MusicService.MusicControl musicControl;
    private String name;
    private Intent intent1,intent2;
    private MyServiceConn conn;
    //记录服务是否被解绑，默认没有
    private boolean isUnbind =false;
    private boolean isUserScrolling = false; // 是否是用户手动滑动
    private boolean isFavorite;
    private int type;
    // 声明变量
    private ImageButton btnPlayPause;
    private ImageButton btnFav;
    private ImageButton btnChat;
    private ImageButton btnNext;
    private ImageButton btnPre;
    private boolean isPlaying = false;
    private boolean isFirst =true;
    private static final long AUTO_SCROLL_TIMEOUT = 3000; // 用户停止滚动后等待的时间，单位毫秒
    private Handler scrollHandler = new Handler(Looper.getMainLooper()); // 用于处理延迟任务
    private Runnable resetScrollRunnable; // 用于取消和重新设置延迟任务

    private static final int REQUEST_NOTIFICATION_PERMISSION = 100;

    private RecyclerView lyricTextView; // 显示歌词的控件
    private static LyricParser lyricParser; // 歌词解析器
    private LyricsAdapter adapter;
    private int position;
    private List<Song> songList;
    private Song song;
    private boolean isSwitchingSong = false;
    private int dur=0;
    private FavoritesDAO favoritesDao;
    // 广播接收器
    private final BroadcastReceiver playStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Objects.equals(intent.getAction(), AppConstants.ACTION_UPDATE_PLAY_BUTTON)) {
                boolean isPlaying1 = intent.getBooleanExtra(AppConstants.EXTRA_IS_PLAYING, false);
                int iconResId = isPlaying1 ? R.drawable.ic_play : R.drawable.ic_pause;
                btnPlayPause.setImageResource(iconResId);
                if(isPlaying1)
                {
                    animator.resume();
                }else{
                    animator.pause();
                }
                isPlaying=isPlaying1;
            }
            if (Objects.equals(intent.getAction(), AppConstants.NEXT))
            {
                btnNext.performClick();
            }
            if (Objects.equals(intent.getAction(), AppConstants.PRE))
            {
                btnPre.performClick();
            }
        }
    };

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onResume() {
        super.onResume();
        Log.d("ActivityStatus", "onResume: 注册广播接收器");
//        // 1. 先读取保存的状态并更新UI
//        SharedPreferences prefs = getSharedPreferences("PlayerPrefs", Context.MODE_PRIVATE);
//        boolean isPlaying1 = prefs.getBoolean(AppConstants.EXTRA_IS_PLAYING, false);
//        int iconResId = isPlaying1 ? R.drawable.ic_play : R.drawable.ic_pause;
//        btnPlayPause.setImageResource(iconResId);
//
//        Log.d("1", String.valueOf(isPlaying1));
        // 2. 注册广播接收器（用于实时更新）
        IntentFilter filter = new IntentFilter(AppConstants.ACTION_UPDATE_PLAY_BUTTON);
        filter.addAction(AppConstants.NEXT);
        filter.addAction(AppConstants.PRE);

        // 动态处理不同API级别
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(
                    playStateReceiver,
                    filter,
                    Context.RECEIVER_EXPORTED  // 改为EXPORTED
            );
        } else {
            registerReceiver(playStateReceiver, filter);
        }

        Log.d("BroadcastDebug", "广播接收器已注册");
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 注销广播接收器
        Log.d("ActivityStatus", "onPause: 注销广播接收器");
        unregisterReceiver(playStateReceiver);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        checkNotificationPermission();
        type=1;
        //获取从frag1传来的信息
        intent1=getIntent();
        // 获取传递过来的歌曲信息
        position = Integer.parseInt(Objects.requireNonNull(getIntent().getStringExtra("position")));
        songList = (List<Song>) getIntent().getSerializableExtra("songList");
        assert songList != null;
        song=songList.get(position);
        favoritesDao = new FavoritesDAO(this);
        isFavorite = false;
        // 添加到最近播放
        RecentPlayDAO recentDao = new RecentPlayDAO(this);
        recentDao.addRecentItem(song.getPath(), 0); // 0 表示歌曲类型
        // 获取专辑封面
        Bitmap albumCover = null;
        try {
            albumCover = getAlbumArt(song.getPath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        song.setAlbumCover(albumCover);
        init();
    }
    // 新增方法：检查通知权限
    private void checkNotificationPermission() {
        // 仅当运行在Android 13（Tiramisu）及以上版本时检查
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                // 解释为什么需要这个权限（可选）
                if (shouldShowRequestPermissionRationale(
                        Manifest.permission.POST_NOTIFICATIONS)) {
                    // 显示解释对话框
                    new AlertDialog.Builder(this)
                            .setTitle("需要通知权限")
                            .setMessage("我们需要通知权限来显示音乐播放控制")
                            .setPositiveButton("确定", (dialog, which) -> {
                                // 再次请求权限
                                requestPermissions(
                                        new String[]{Manifest.permission.POST_NOTIFICATIONS},
                                        REQUEST_NOTIFICATION_PERMISSION
                                );
                            })
                            .setNegativeButton("取消", null)
                            .create()
                            .show();
                } else {
                    // 直接请求权限
                    requestPermissions(
                            new String[]{Manifest.permission.POST_NOTIFICATIONS},
                            REQUEST_NOTIFICATION_PERMISSION
                    );
                }
            }
        }
    }

    // 新增方法：处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_NOTIFICATION_PERMISSION) {
            if (grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已授予，可以显示通知
                Toast.makeText(this, "通知权限已授予", Toast.LENGTH_SHORT).show();
            } else {
                // 权限被拒绝
                Toast.makeText(this, "您拒绝了通知权限，将无法显示播放控制",
                        Toast.LENGTH_LONG).show();
            }
        }
    }

    private void init(){

        btnPlayPause=findViewById(R.id.btn_play_pause);
        btnNext=findViewById(R.id.btn_next);
        btnPre=findViewById(R.id.btn_previous);
        btnFav=findViewById(R.id.btn_favorite);
        btnChat=findViewById(R.id.btn_chat);
        instance = this;
        // 初始化歌词 TextView
        lyricTextView = findViewById(R.id.rv_lyrics);
        lyricTextView.setLayoutManager(new LinearLayoutManager(this));
        lyricTextView.setHasFixedSize(true);
        // 初始化 lyricParser 并加载歌词
        lyricParser = new LyricParser();
        if(song.getLyricsPath()==null)
        {
            InputStream inputStream = getResources().openRawResource(R.raw.music);
            try {
                lyricParser.parse(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try (FileInputStream fis = new FileInputStream(song.getLyricsPath())) {
                lyricParser.parse(fis); // 传入 InputStream
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        // 检查是否成功加载了歌词
        Map<Integer, String> lyricMap = lyricParser.getLyricMap();
        if (lyricMap == null || lyricMap.isEmpty()) {
            // 处理没有歌词或加载失败的情况
            Log.e("MusicActivity", "Failed to load lyrics or no lyrics available.");
            return;
        }
        List<String> lyricsList = new ArrayList<>(lyricParser.getLyricMap().values());
        adapter = new LyricsAdapter(lyricsList);
        lyricTextView.setAdapter(adapter);

        lyricTextView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING || newState == RecyclerView.SCROLL_STATE_SETTLING) {
                    isUserScrolling = true;
                    // 取消之前可能存在的延迟任务
                    if (resetScrollRunnable != null) {
                        scrollHandler.removeCallbacks(resetScrollRunnable);
                    }
                } else if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 当用户停止滚动时，启动一个新的延迟任务
                    resetScrollRunnable = () -> {
                        isUserScrolling = false;
                    };
                    scrollHandler.postDelayed(resetScrollRunnable, AUTO_SCROLL_TIMEOUT);
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 可选：在这里也可以做更复杂的逻辑判断
            }
        });

        //进度条上小绿点的位置，也就是当前已播放时间
        tv_progress=(TextView)findViewById(R.id.tv_progress);
        //进度条的总长度，就是总时间
        tv_total=(TextView)findViewById(R.id.tv_total);
        //进度条的控件
        sb=(SeekBar)findViewById(R.id.sb);
        //歌曲名显示的控件
        name_song=(TextView)findViewById(R.id.song_name);
        imageView=(ImageView)findViewById(R.id.iv_music);
        lyricTextView=(RecyclerView)findViewById(R.id.rv_lyrics);
        //绑定控件的同时设置点击事件监听器
        findViewById(R.id.btn_play_pause).setOnClickListener(this);
        findViewById(R.id.btn_exit).setOnClickListener(this);
        findViewById(R.id.btn_switch_image).setOnClickListener(this);
        findViewById(R.id.btn_switch_text).setOnClickListener(this);
        findViewById(R.id.btn_favorite).setOnClickListener(this);
        findViewById(R.id.btn_chat).setOnClickListener(this);
        findViewById(R.id.btn_next).setOnClickListener(this);
        findViewById(R.id.btn_previous).setOnClickListener(this);
        findViewById(R.id.btn_menu).setOnClickListener(this);
        findViewById(R.id.btn_download).setOnClickListener(this);

        name=song.getTitle()+"——"+song.getArtist();
        name_song.setText(name);
        //创建一个意图对象，是从当前的Activity跳转到Service
        intent2=new Intent(this,MusicService.class);
        conn=new MyServiceConn();//创建服务连接对象
        bindService(intent2,conn,BIND_AUTO_CREATE);//绑定服务
        //为滑动条添加事件监听，每个控件不同果然点击事件方法名都不同
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            private Handler seekBarHandler = new Handler(Looper.getMainLooper());
            private Runnable nextSongRunnable = new Runnable() {
                @Override
                public void run() {
                    animator.pause();
                    musicControl.pausePlay();
                    btnNext.performClick(); // 执行点击事件
                }
            };

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 如果进度条当前在最大值
                if (progress >= seekBar.getMax()-8) {

                    // 先移除旧任务，防止重复触发
                    seekBarHandler.removeCallbacks(nextSongRunnable);

                    // 延迟 3 秒执行
                    seekBarHandler.postDelayed(nextSongRunnable, 3000);
                } else {
                    // 进度不是 max，取消延迟任务
                    seekBarHandler.removeCallbacks(nextSongRunnable);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 可以在这里暂停自动更新进度条
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                if(progress>dur)
                {
                    progress=dur;
                }else if(progress < 0) {
                    progress = 0;
                }
                musicControl.seekTo(progress);
            }
        });
        //声明并绑定音乐播放器的iv_music控件
        if(song.getAlbumCover()!=null){
            imageView.setImageBitmap(song.getAlbumCover());
        }else {
            imageView.setImageResource(R.drawable.default_album_art);
        }
        //rotation和0f,360.0f就设置了动画是从0°旋转到360°
        animator=ObjectAnimator.ofFloat(imageView,"rotation",0f,360.0f);
        animator.setDuration(10000);//动画旋转一周的时间为10秒
        animator.setInterpolator(new LinearInterpolator());//匀速
        animator.setRepeatCount(-1);//-1表示设置动画无限循环

        isFavorite = song.isFavorite(this);
        int iconRes = isFavorite ? R.drawable.ic_favorite1 : R.drawable.ic_favorite;
        btnFav.setImageResource(iconRes);
    }

    // 提供一个方法来获取 adapter 实例
    public LyricsAdapter getLyricsAdapter() {
        return adapter;
    }

    //handler机制，可以理解为线程间的通信，我获取到一个信息，然后把这个信息告诉你，就这么简单
    public static Handler handler=new Handler(){
        //创建消息处理器对象
        //在主线程中处理从子线程发送过来的消息
        @Override
        public void handleMessage(Message msg){

            Bundle bundle=msg.getData();//获取从子线程发送过来的音乐播放进度
            //获取当前进度currentPosition和总时长duration
            int duration=bundle.getInt("duration");
            int currentPosition=bundle.getInt("currentPosition");
            //对进度条进行设置
            sb.setMax(duration);
            sb.setProgress(currentPosition);
            //歌曲是多少分钟多少秒钟
            int minute=duration/1000/60;
            int second=duration/1000%60;
            String strMinute=null;
            String strSecond=null;
            if(minute<10){
                //如果歌曲的时间中的分钟小于10
                strMinute="0"+minute;//在分钟的前面加一个0
            }else{

                strMinute=minute+"";
            }
            if (second<10){
                //如果歌曲中的秒钟小于10
                strSecond="0"+second;//在秒钟前面加一个0
            }else{

                strSecond=second+"";
            }
            //这里就显示了歌曲总时长
            tv_total.setText(strMinute+":"+strSecond);
            //歌曲当前播放时长
            minute=currentPosition/1000/60;
            second=currentPosition/1000%60;
            if(minute<10){
                //如果歌曲的时间中的分钟小于10
                strMinute="0"+minute;//在分钟的前面加一个0
            }else{

                strMinute=minute+" ";
            }
            if (second<10){
                //如果歌曲中的秒钟小于10
                strSecond="0"+second;//在秒钟前面加一个0
            }else{

                strSecond=second+" ";
            }
            //显示当前歌曲已经播放的时间
            tv_progress.setText(strMinute+":"+strSecond);

            int highlightPos = -1;

            // 获取排序好的歌词列表（按时间升序）
            List<Map.Entry<Integer, String>> entries = new ArrayList<>(instance.lyricParser.getLyricMap().entrySet());

            int currentSecond = currentPosition / 1000;
            for (int i = 0; i < entries.size(); i++) {
                Map.Entry<Integer, String> entry = entries.get(i);
                if (entry.getKey() <= currentSecond) {
                    highlightPos = i;
                } else {
                    break;
                }
            }

            if (highlightPos >= 0 && instance.adapter != null && !instance.isUserScrolling) {
                instance.adapter.setHighlightedPosition(highlightPos);
                instance.adapter.notifyDataSetChanged();
                final int highlightPosCopy = highlightPos;
                instance.lyricTextView.post(() -> {
                    int middleOfScreen = instance.lyricTextView.getHeight() / 2;
                    View firstVisibleItemView = instance.lyricTextView.getChildAt(0);
                    Log.d("123", String.valueOf(middleOfScreen));
                    if (firstVisibleItemView != null) {
                        int itemHeight = firstVisibleItemView.getHeight();
                        int offset = middleOfScreen - itemHeight / 2;

                        ((LinearLayoutManager) instance.lyricTextView.getLayoutManager())
                                .scrollToPositionWithOffset(highlightPosCopy, offset);
                        Log.d("321", String.valueOf(itemHeight));
                    }
                });
            }
        }
    };

    //用于实现连接服务，比较模板化，不需要详细知道内容
    class MyServiceConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service){

            musicControl=(MusicService.MusicControl) service;

            btnPlayPause.performClick();
        }
        @Override
        public void onServiceDisconnected(ComponentName name){


        }
    }
    //判断服务是否被解绑
    private void unbind(boolean isUnbind){

        //如果解绑了
        if(!isUnbind){

            musicControl.pausePlay();//音乐暂停播放
            unbindService(conn);//解绑服务
        }
    }
    @Override
    public void onClick(View v) {

        int id=v.getId();
        if(id==R.id.btn_play_pause)
        {
            Intent serviceIntent = new Intent(this, MusicService.class);
            if (isPlaying) {
                // 如果正在播放，则切换到暂停图标
                btnPlayPause.setImageResource(R.drawable.ic_pause); // 注意：应替换为实际的暂停图标资源
                musicControl.pausePlay();
                animator.pause();
                serviceIntent.setAction(MusicService.ACTION_PAUSE);
            } else {
                if(isFirst)
                {
                    // 如果没有播放，则切换到播放图标
                    btnPlayPause.setImageResource(R.drawable.ic_play); // 注意：应替换为实际的播放图标资源
                    try {
                        dur=musicControl.play(song.getPath());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    musicControl.fir(name);
                    if(!animator.isStarted())
                    {
                        animator.start();
                    }
                    isFirst=false;
                }
                else{
                    btnPlayPause.setImageResource(R.drawable.ic_play);
                    musicControl.continuePlay();
                    animator.resume();
                }
                serviceIntent.setAction(MusicService.ACTION_PLAY);
            }
            isPlaying = !isPlaying; // 切换标记状态
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(serviceIntent);
            } else {
                startService(serviceIntent);
            }
        }else if(id==R.id.btn_exit){
            //unbind(isUnbind);
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("song", song);
            intent.putExtra("songList", new ArrayList<>(songList));
            intent.putExtra("isPlaying",isPlaying);
            intent.putExtra("position",position);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            dur=0;
            isUnbind=true;
            animator.cancel();
            finish(); // 关闭当前页面
            overridePendingTransition(0, 0);
        } else if (id==R.id.btn_favorite) {
            // 切换收藏状态
            isFavorite = !isFavorite;

            // 更新数据库
            if (isFavorite) {
                favoritesDao.addFavorite(song.getPath());
            } else {
                favoritesDao.removeFavorite(song.getPath());
            }

            // 更新UI
            updateFavoriteIcon();
            // 显示提示信息
            String message = isFavorite ? "已添加到收藏" : "已取消收藏";
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        } else if (id==R.id.btn_chat) {
            if(type==1)
            {
                btnChat.setImageResource(R.drawable.ic_chat1);
                type=2;
            } else if (type==2) {
                btnChat.setImageResource(R.drawable.ic_chat2);
                type=3;
            }else {
                btnChat.setImageResource(R.drawable.ic_chat);
                type=1;
            }
        } else if (id==R.id.btn_next) {
            if (isSwitchingSong) return; // 锁住时不响应点击

            isSwitchingSong = true;
            if(type==1)
            {
                position=(position+1)%songList.size();
            } else if (type==2) {

            }else {
                Random random = new Random();
                int nextPos;

                do {
                    nextPos = random.nextInt(songList.size());
                } while (nextPos == position); // 避免重复播放同一首歌
                position=nextPos;
            }

            move(position);
        } else if (id==R.id.btn_previous) {
            if (isSwitchingSong) return; // 锁住时不响应点击

            isSwitchingSong = true;
            if(type==1)
            {
                position = ((position - 1) % songList.size() + songList.size()) % songList.size();
            } else if (type==2) {

            }else {
                Random random = new Random();
                int nextPos;

                do {
                    nextPos = random.nextInt(songList.size());
                } while (nextPos == position);
                position=nextPos;
            }
            move(position);
        } else if (id==R.id.btn_menu) {
            PlaylistDialogFragment dialog = PlaylistDialogFragment.newInstance(songList,position);
            dialog.show(getSupportFragmentManager(), "playlist");
        } else if (id==R.id.btn_download) {
           setRingtone();
        } else if(id==R.id.btn_switch_image){
            imageView.setVisibility(View.VISIBLE);
            lyricTextView.setVisibility(View.GONE);
        }else if(id==R.id.btn_switch_text){
            imageView.setVisibility(View.GONE);
            lyricTextView.setVisibility(View.VISIBLE);
        }
    }

    // 1. 定义请求码（放在类顶部）
    private static final int REQUEST_CODE_WRITE_SETTINGS = 1001;

    // 2. 设置铃声的主方法
    public void setRingtone() {
        // 检查并请求 WRITE_SETTINGS 权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(getApplicationContext())) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_CODE_WRITE_SETTINGS);
                return; // 等待权限回调
            }
        }

        // 3. 处理文件URI（兼容Android 7.0+）
        Uri audioUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+：使用MediaStore
            audioUri = getMediaStoreUri(song.getPath());
        } else {
            // Android 7.0-9.0：使用FileProvider
            audioUri = FileProvider.getUriForFile(
                    this,
                    getPackageName() + ".fileprovider",
                    new File(song.getPath())
            );
        }

        // 4. 确保文件在铃声目录（关键步骤！）
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            copyFileToRingtonesDir(song.getPath());
        }

        // 5. 设置铃声
        try {
            RingtoneManager.setActualDefaultRingtoneUri(
                    getApplicationContext(),
                    RingtoneManager.TYPE_RINGTONE,
                    audioUri
            );
            Toast.makeText(this, "铃声设置成功", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "设置失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    // 3. 处理权限回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_WRITE_SETTINGS) {
            // 重新检查权限是否被授予
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (Settings.System.canWrite(this)) {
                    // 权限已授予，执行设置铃声操作
                    setRingtone();
                } else {
                    Toast.makeText(this, "未授予权限，无法设置铃声", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // 复制文件到系统铃声目录（确保系统能识别）
    private void copyFileToRingtonesDir(String sourcePath) {
        File sourceFile = new File(sourcePath);
        File destDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_RINGTONES
        );
        File destFile = new File(destDir, sourceFile.getName());

        try (InputStream in = new FileInputStream(sourceFile);
             OutputStream out = new FileOutputStream(destFile)) {
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 通知系统刷新媒体库
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(destFile)));
    }

    // Android 10+ 获取MediaStore URI
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private Uri getMediaStoreUri(String filePath) {
        ContentResolver resolver = getContentResolver();
        File file = new File(filePath);
        ContentValues values = new ContentValues();
        values.put(MediaStore.Audio.Media.TITLE, file.getName());
        values.put(MediaStore.Audio.Media.RELATIVE_PATH, Environment.DIRECTORY_RINGTONES);

        Uri uri = resolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
        try (OutputStream os = resolver.openOutputStream(uri);
             InputStream is = new FileInputStream(file)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return uri;
    }

    @Override
    public void onSongSelected(int posi_1) {
        if (isSwitchingSong) return;

        isSwitchingSong = true;
        move(posi_1);   // 切换歌曲
        position=posi_1;
    }
    private void move(int pos)
    {
        song=songList.get(pos);
        name=song.getTitle()+"——"+song.getArtist();
        name_song.setText(name);
        Bitmap albumCover = null;
        try {
            albumCover = getAlbumArt(song.getPath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        song.setAlbumCover(albumCover);
        lyricParser = new LyricParser();
        if(song.getLyricsPath()==null)
        {
            InputStream inputStream = getResources().openRawResource(R.raw.music);
            try {
                lyricParser.parse(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try (FileInputStream fis = new FileInputStream(song.getLyricsPath())) {
                lyricParser.parse(fis); // 传入 InputStream
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map<Integer, String> lyricMap = lyricParser.getLyricMap();
        if (lyricMap == null || lyricMap.isEmpty()) {
            // 处理没有歌词或加载失败的情况
            Log.e("MusicActivity", "Failed to load lyrics or no lyrics available.");
            return;
        }
        List<String> lyricsList = new ArrayList<>(lyricParser.getLyricMap().values());
        adapter = new LyricsAdapter(lyricsList);
        lyricTextView.setAdapter(adapter);
        isPlaying=false;
        isFirst=true;

        btnPlayPause.performClick();
        if (animator.isRunning()) {
            animator.cancel();
        }
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            imageView.setImageBitmap(song.getAlbumCover());
            animator.start();
            isSwitchingSong=false;
        }, 50); // 短延迟确保状态重置完成
    }

    // 获取专辑封面
    private Bitmap getAlbumArt(String filePath) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            byte[] artBytes = retriever.getEmbeddedPicture();
            if (artBytes != null) {
                return BitmapFactory.decodeByteArray(artBytes, 0, artBytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return null;
    }

    // 更新收藏按钮图标
    private void updateFavoriteIcon() {
        int iconRes = isFavorite ? R.drawable.ic_favorite1 : R.drawable.ic_favorite;
        btnFav.setImageResource(iconRes);
    }

    @Override
    protected void onDestroy(){

        super.onDestroy();
        unbind(isUnbind);//解绑服务
    }

}